#ifndef DOWNLOADER_H
#define DOWNLOADER_H

#include <QNetworkAccessManager>
#include <QString>
#include <QDir>
#include <QFile>
#include <vector>

#include "writer.h"
using namespace std;

// almost all functions of gui control

class Downloader : public QObject
{
    Q_OBJECT

public:
    Downloader(QObject* parent = nullptr);
    ~Downloader();

    void startDownload(const QString& url_str, const QDir& saveDir, QString filename, int nt);

signals:
    void progressChanged(int prg);          // emits when progress is changed
    void finished();                        // emitted when downloading finished
    void errorOccured(QString error);            // when an error occurs

private slots:
    void headerReceived(QNetworkReply* reply);
    void newDataDownloaded(qint64 n);         // n bytes more downloaded
    void onError(QNetworkReply::NetworkError error);
    void onFinished(QNetworkReply* reply);

private:
    void initRequests(int nt, qint64 contentLength);
    void downloadUsingSingleConnection();

    QFile* file;                            // save data to this file
    QDir saveDir;                           // save to this directory
    QUrl url;
    int nt;                                 // number of threads
    qint64 contentLength;                   // file size
    qint64 downloaded;                  // total bytes downloaded from all threads
};

#endif // DOWNLOADER_H
